#    Copyright 2008, 2009 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPGIS.
#    COOPGIS is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPGIS is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPGIS.  If not, see <http://www.gnu.org/licenses/>.

#************************BEGIN Add Include Files to Path************************
import sys
NeededPaths=['/opt/coopgis/djangoproject/include', '/opt/coopgis/djangoproject']
for path in NeededPaths:
    if(not path in sys.path):
        sys.path.append(path)
#************************END   Add Include Files to Path************************
import COOPGIS_Ajax, COOPGIS_GPS, COOPGIS_Misc, COOPGIS_ReportLab, COOPGIS_String, COOPGIS_Update
import os, csv, shutil, datetime, time, reportlab, djangoproject.settings, random
from django.contrib.gis.db import models
from django.contrib.gis.geos import *
from django.http import HttpResponse
from django.contrib import admin
from django.template import Context, loader
import djangoproject.settings
import _mysql as mysql
from models import *
from django import forms
import datetime



def index(request):
    """index returns the main menu screen, same as the index file in Misc.py"""
    if request.user.is_anonymous():
        LoginStatus="You are not currently logged in."
    else:
        LoginStatus="Welcome to COOPGIS, " + request.user.username + '.'
    ServerIndicator=djangoproject.settings.COOPGISServerIndicator   
    t = loader.get_template('/opt/coopgis/djangoproject/templates/mainmenu.html')
    c = Context({'LoginStatus': LoginStatus, 'ServerIndicator': ServerIndicator})
    return HttpResponse(t.render(c))

def ClientStartUpdate(request):
    """ClientStartUpdate is the view that the User clicks on the client machine to update it to the latest version.  It triggers the update process
       and redirects the user to the Update Status Page"""
    if request.user.is_anonymous():
        t=loader.get_template('/opt/coopgis/djangoproject/templates/clientstartupdate.html')
        c=Context({'UpdateMessage': 'You must be logged in order to initiate an update'})
        return HttpResponse(t.render(c))
    if(djangoproject.settings.COOPGISServerIndicator):
        return index(request)  #This view only works on a client machine
    if(os.system('ping ' + djangoproject.settings.COOPGISServerIPAddress + ' -c 1')):
        raise(Exception('Could not connect to the server:  ' +  djangoproject.settings.COOPGISServerIPAddress + '  Check your network connection.'))
    LastUpdateTime=COOPGIS_Update.GetLastUpdateDateTime()
    TimeSinceLastUpdate=datetime.datetime.now() - LastUpdateTime
    SecondsSinceLastUpdate=TimeSinceLastUpdate.seconds
    TimeBetweenUpdates = 60 * 30 #seconds * minutes
    if(TimeSinceLastUpdate.days == 0) and (TimeSinceLastUpdate.seconds < TimeBetweenUpdates): 
        SecondsLeft = TimeBetweenUpdates - TimeSinceLastUpdate.seconds
        raise(Exception('You must wait:  ' + str(TimeBetweenUpdates) + ' seconds between updates.\
                         Time left until you can update again:  ' + str(SecondsLeft) + ' seconds.\n'))
        return index(request) #Make sure exception is not caught somewhere..
    COOPGIS_Update.WriteUpdateStatus('Starting Update Process in ClientStartUpdate, Creating the Update Number.')   

    COOPGIS_Update.WriteUpdateStatus('StartImageMagick Install')   
    os.system("sudo -u apachescript sudo apt-get install imagemagick -y")
    COOPGIS_Update.WriteUpdateStatus('EndImageMagick Install')   

    #Create the Update Number, based on the current date time along with a random number
    RandomNumber=str(random.randint(100000, 999999))
    Now=datetime.datetime.now()
    Year=COOPGIS_String.LeadingZero(str(Now.year))
    Month=COOPGIS_String.LeadingZero(str(Now.month))
    Day=COOPGIS_String.LeadingZero(str(Now.day))
    Hour=COOPGIS_String.LeadingZero(str(Now.hour))
    Minute=COOPGIS_String.LeadingZero(str(Now.minute))
    Second=COOPGIS_String.LeadingZero(str(Now.second))
    UpdateNumber=Year + Month + Day + '_' + Hour + Minute + Second + '_' + RandomNumber
    UpdateMessage='The COOPGIS update process has started.  Your browser is automatically being redirected to the Update Status Page.'
    COOPGIS_Update.ClientPerformUpdateTasks(UpdateNumber)   
    t=loader.get_template('/opt/coopgis/djangoproject/templates/clientstartupdate.html')
    c=Context({'UpdateNumber': UpdateNumber, 'UpdateMessage': UpdateMessage})
    return HttpResponse(t.render(c))


def ServerProcessCommands(request, UpdateNumber):
    if(Command.objects.filter(CommandUpdateNumber=UpdateNumber).filter(CommandProcessedIndicator=True).count()):   
        return index(request)  #Prevents processing commands multiple times, need to process manually if an update partially completes
    Commands=Command.objects.filter(CommandUpdateNumber=UpdateNumber).order_by('id')
    for command in Commands:
        try:
            command.Process()
        except:
            command.CommandProcessFailedIndicator=True
            command.save()
    return index(request)

def ClientDisplayUpdateStatus(request, UpdateNumber=None):
    """Once an update has been initiated, the Client's browser will be redirected to this view.  It will keep the user informed as to the 
    status of the update process."""
    if(len(UpdateNumber) <> 22):  #22 character update number is expected (YYYYMMDD_HHMMSS_RRRRRR) Hides the page a bit from the user
        return index(request) 
    if(djangoproject.settings.COOPGISServerIndicator):
        return index(request) #This view only works on a client machine
    RefreshDelay=3 #Default Update User every 3 seconds
    try:
        UpdateStatus=GetUpdateStatus()
    except:
        return index(request)
    if(UpdateStatus.find('Rebooting') <> -1):
        RefreshDelay=180 #Wait 3 minutes for reboot to complete, users will figure out if impatient they can go to the main menu
    t=loader.get_template('/opt/coopgis/djangoproject/templates/clientdisplayupdatestatus.html')
    c=Context({'RefreshDelay': RefreshDelay, 'UpdateNumber': UpdateNumber,'UpdateStatus': UpdateStatus})
    return HttpResponse(t.render(c))

def ServerImportCommands(request, UpdateNumber=None):
    """ServerImportCommands is the view that is run on the server machine by a client when it is updating to the latest version.  It Imports 
    a list of commands in the /COOPGISUpdatePathFTP/UpdateNumber.pickle file."""
    if(len(UpdateNumber) <> 22):  #22 character update number is expected (YYYYMMDD_HHMMSS_RRRRRR)
        return index(request) #Do not process this update if the format does not match
    JustUploadedFileName=djangoproject.settings.COOPGISUpdatePathFTP + UpdateNumber + '.pickle'
    InProgressFileName=djangoproject.settings.COOPGISUpdatePathInProgress + UpdateNumber + '.pickle'
    CompletedFileName=djangoproject.settings.COOPGISUpdatePathCompleted + UpdateNumber + '.pickle'
    os.system("sudo -u apachescript sudo mkdir " + djangoproject.settings.COOPGISUpdatePathFTPRootReadOnly)
    os.system("sudo -u apachescript sudo chmod 777 " + djangoproject.settings.COOPGISUpdatePathFTPRootReadOnly)
    os.system("sudo -u apachescript sudo mkdir " + djangoproject.settings.COOPGISUpdatePathFTP)
    os.system("sudo -u apachescript sudo mkdir " + djangoproject.settings.COOPGISUpdatePathInProgress)
    os.system("sudo -u apachescript sudo mkdir " + djangoproject.settings.COOPGISUpdatePathCompleted)
    os.system("sudo -u apachescript sudo chmod 555 " + djangoproject.settings.COOPGISUpdatePathFTPRootReadOnly)
    os.system("sudo -u apachescript sudo chmod -R 777 " + djangoproject.settings.COOPGISUpdatePathFTP)
    os.system("sudo -u apachescript sudo chmod -R 777 " + djangoproject.settings.COOPGISUpdatePathInProgress)
    os.system("sudo -u apachescript sudo chmod -R 777 " + djangoproject.settings.COOPGISUpdatePathCompleted)
    if(os.path.exists(InProgressFileName)):
        raise(Exception('In Progress File Name Existed at the start of ServerImportCommands'))
    if(os.path.exists(CompletedFileName)):
        raise(Exception('Completed File Name Existed at the start of ServerImportCommands'))
    shutil.move(JustUploadedFileName, InProgressFileName)
    os.system("sudo -u apachescript sudo chmod 777 " + InProgressFileName)
    COOPGIS_Update.ServerWaitUntilEarlierUpdatesAreProcessed(UpdateNumber, InProgressFileName)
    command=Command()
    command.ImportFromTextFile(TextFileName=InProgressFileName, UpdateNumber=UpdateNumber, ProcessIndicator=False, VerifyIndicator=True)
    shutil.move(InProgressFileName, CompletedFileName)
    NumberOfCommandsImported=str(len(Command.objects.filter(CommandUpdateNumber=UpdateNumber).exclude(CommandProcessedIndicator=True))) 
    t=loader.get_template('/opt/coopgis/djangoproject/templates/serverimportcommands.html')
    c=Context({'NumberOfCommandsImported': NumberOfCommandsImported})
    return HttpResponse(t.render(c))
        
def ServerUpdateRepository(request):
    """View that updates the Mercurial Repository on the Server before a Client Downloads it"""
    IPAddress=str(request.META['REMOTE_ADDR'])
    if(':' in IPAddress):
        IPAddress = 'localhost'
    COOPGIS_Update.SetResidesOnServerIndicatorToTrueForAllCommands()  # For commands that do not have this set for any reason
    SpecificRepositoryDirectory = COOPGIS_Update.ServerProtectedDumpDatabaseAndPullRepository(IPAddress)
    return HttpResponse('Your Download Location:' + SpecificRepositoryDirectory)

def ServerGetSizeOfDatabaseFile(request):
    IPAddress=str(request.META['REMOTE_ADDR'])
    return HttpResponse(str(os.path.getsize('/var/www/downloadrepository/' + IPAddress + '/opt/coopgis/DataNotPartOfCOOPGIS/Latest.sql')))

